﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace MSN {    
    public class BluetoothListener {

        public static void ChooseDevice() {
            try {
                InTheHand.Windows.Forms.SelectBluetoothDeviceDialog diag = new InTheHand.Windows.Forms.SelectBluetoothDeviceDialog();

                if(diag.ShowDialog() == DialogResult.OK && diag.SelectedDevice != null) {
                    device = diag.SelectedDevice;
                    if(device != null) {
                        CurrentState = true;
                        timer = new System.Threading.Timer(new System.Threading.TimerCallback(ScanBT), null, PollingFrequency / 2, PollingFrequency);
                    }
                }
            } catch(Exception exc) {
                System.Windows.Forms.MessageBox.Show("ChooseDevice" + exc.ToString());
            }
        }
        public static void Disconnect() {
            if(device != null) device = null;
            if(timer!=null) timer.Dispose();
        }

        public delegate void DeviceChanged(InTheHand.Net.Sockets.BluetoothDeviceInfo Device, bool Connected);
        public static event DeviceChanged OnDeviceChanged;

        public static int PollingFrequency = 10000;
        static InTheHand.Net.Sockets.BluetoothDeviceInfo device;
        static System.Threading.Timer timer = null;
        private static bool CurrentState = false;
        static object locker = new object();
        static InTheHand.Net.Sockets.BluetoothClient c = new InTheHand.Net.Sockets.BluetoothClient();


        private static void ScanBT(object state) {
            try {
                lock(locker) {
                    InTheHand.Net.Sockets.BluetoothDeviceInfo[] devices = c.DiscoverDevices();
                    bool found = false;
                    foreach(InTheHand.Net.Sockets.BluetoothDeviceInfo d in devices) {
                        if(d.DeviceName == device.DeviceName) {
                            found = true;
                            break;
                        }
                    }
                    if(CurrentState && !found) {
                        if(OnDeviceChanged != null) OnDeviceChanged(device, false);
                    }
                    if(!CurrentState && found) {
                        if(OnDeviceChanged != null) OnDeviceChanged(device, true);
                    }
                    CurrentState = found;
                }
            } catch(Exception exc) {
                System.Windows.Forms.MessageBox.Show("ScanBT" + exc.ToString());
            }
        }
    }
}
